<template>
  <div class="tableList">
    <!-- <div
      :class="{ both: slots.title && slots.extra, toolBar: true }"
      v-if="slots.title || slots.extra"
    >
      <slot name="title"></slot>
      <div class="alignRight">
        <slot name="extra"></slot>
      </div>
    </div> -->
    <el-table
      v-loading="loading"
      :pagination="pagination"
      :data="tableData"
      v-bind="$attrs"
      ref="tableRef"
    >
      <el-table-column
         label="序号"
      >
        <template #default="{ row, $index }">
          <!-- 序号 -->
          <span>
            {{ (pagination.current - 1) * pagination.pageSize + $index + 1 }}
          </span>


        </template>

      </el-table-column>
      <template v-for="item in columns">
        <el-table-column v-bind="item" v-if="item?.formatter"></el-table-column>
        <el-table-column
            :show-overflow-tooltip="true"
            v-bind="item"
            v-else
        >
          <template v-if="!notRenderType.includes(item.type)" #default="{ row, $index }">
            <!-- 序号 -->
            <span v-if="item.type === 'index'">
            {{ (pagination.current - 1) * pagination.pageSize + $index + 1 }}
          </span>
            <!-- 自定义内容 -->
            <slot v-else-if="item.slot" :name="item.slot" :row="row" :index="$index"></slot>
            <!-- 没有值时默认展示 -->
            <span v-else>{{ row[item.prop] || "--" }}</span>
          </template>
          <!-- <template #content="{ row }" v-if="item.content">
            <slot :name="item.content" :row="row"></slot>
          </template> -->
        </el-table-column>
      </template>

    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :hide-on-single-page="true"
        :total="pagination.total"
        v-model:page-size="pagination.pageSize"
        v-model:current-page="pagination.current"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, useSlots, watchEffect ,watch} from "vue";
const emit = defineEmits(["pageChange", "selectAllChange", "selectChange"]);
const slots = useSlots();
const props = defineProps({
  columns: {
    type: Array,
    default: () => [],
  },
  // 传入请求方法
  request: {
    type: Function,
  },
  // 传入请求后的数据
  dataSource: {
    type: Array,
    default: null,
  },
  showOverflowTooltip: {
    type: Boolean,
    default: true,
  },
  params:{
    type: Object,
    default:{}
  }
});
watch(()=>props.params,val=>{
  if(props.request){
    getData(true);
  }
})
// const contentRef = inject("content");
const loading = ref(false);
const tableData = ref([]);
const tableRef = ref(null);
// 不渲染默认插槽的column type
const notRenderType = ["selection"];
// 分页默认数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
/**
 * @description: 分页改变
 * @param {*} page
 * @param {*} pageSize
 * @return {*}
 */
const paginationChange = async (page, pageSize) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  props.request && (await getData());
  emit("pageChange", page, pageSize);
};

watch(()=>pagination.current,val=>{
  paginationChange(pagination.current,pagination.pageSize)
})
watch(()=>pagination.pageSize,val=>{
  paginationChange(pagination.current,pagination.pageSize)
})

// 铺满当前容器高度
// const tableHeight = computed(() => {
//   return contentRef.value?.offsetHeight - 48 + "px" || "auto";
// });
/**
 * @description: 获取表格信息  reset为true时重置分页，用于搜索等场景
 * @return {*}
 */
const getData = async (reset = false) => {
  // 是否重置分页，多用于重新请求数据
  if (reset) pagination.current = 1;
  // 传入的是方法
  if (props.request) {
    try {
      loading.value = true;
      const res = await props.request({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...props.params
      });
      loading.value = false;
      if (res) {
        // 分页查询
        tableData.value = res.data || [];
        pagination.total = res.meta.total * 1;
      }
    } catch (error) {
      loading.value = false;
      console.log(error);
    }
  }
};

// const selectAllChangeEvent = ({ checked }) => {
//   emit("selectAllChange", { checked, records: toRaw(tableData.value) });
// };

// const selectChangeEvent = (data) => {
//   emit("selectChange", toRaw(data));
// };
/**
 * @description: 设置选中项目
 * @param {*} key
 * @param {*} rowList
 * @param {*} chekcked
 * @return {*}
 */
// const setRowChecked = (key, rowKeyList, chekcked) => {
//   const list = tableData.value.filter((item) => rowKeyList.includes(item[key]));
//   nextTick(() => {
//     tableRef?.value?.methods("setCheckboxRow")(list, chekcked);
//   });
// };
/**
 * @description: 关闭所有行展开
 * @return {*}
 */
// const clearRowExpand = () => {
//   tableRef?.value?.methods("clearRowExpand")();
// };
// 外部传入数据
if (props.dataSource) {
  watchEffect(() => {
    pagination.total = props.dataSource.length;
    tableData.value = props.dataSource.slice(
      (pagination.current - 1) * pagination.pageSize,
      pagination.pageSize * pagination.current,
    );
  });
}
const setCurrent = (row) => {
  tableRef.value.setCurrentRow(row);
};
// 传入的是方法 获取数据
if (props.request) {
  getData();
}
// 用于外部刷新数据  ref.xxx
defineExpose({
  getData,
  tableData,
  setCurrent,
  //  setRowChecked,
  //  clearRowExpand
});
</script>

<style lang="scss" scoped>
.tableList {
  display: flex;
  flex-direction: column;
  // min-height: v-bind(tableheight);
  .toolBar {
    margin-bottom: 16px;
  }
  .both {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}


</style>
